import {
  queryMainProductList,
  addMainProductList,
  updateMainProductList,
  deleteMainProductList,
} from '@/services/MainProduct';

export default {
  namespace: 'MainProduct',

  state: {
    productList: {},
    updateDidFinish: false,
  },

  effects: {
    *queryMainProductList({ payload }, { call, put }) {
      const response = yield call(queryMainProductList, payload.page_num, payload.page_size);
      yield put({
        type: 'setPayload',
        payload: {
          productList: response.data,
        },
      });
    },
    *addMainProductList({ payload }, { call, put }) {
      const response = yield call(
        addMainProductList,
        payload.product_name,
        payload.product_type_id
      );
      yield put({
        type: 'setPayload',
        payload: {
          updateDidFinish: new Date().getTime(),
        },
      });
    },
    *updateMainProductList({ payload }, { call, put }) {
      const response = yield call(
        updateMainProductList,
        payload.product_name,
        payload.product_type_id,
        payload.id
      );
      yield put({
        type: 'setPayload',
        payload: {
          updateDidFinish: new Date().getTime(),
        },
      });
    },
    *deleteMainProductList({ payload }, { call, put }) {
      const response = yield call(deleteMainProductList, payload.id);
      yield put({
        type: 'setPayload',
        payload: {
          updateDidFinish: new Date().getTime(),
        },
      });
    },
  },

  reducers: {
    setPayload(state, action) {
      return {
        ...state,
        ...action.payload,
      };
    },
  },
};
